﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebPortal.Models.EntityModels;
using WebPortal.Models.ViewModel;

namespace WebPortal.Controllers
{
    public class UsersController : BaseController
    {
        //
        // GET: /Categories/

        public ActionResult Index()
        {
            List<UserGoodsModel> userGoods = new List<UserGoodsModel>();
            var users = (from u in dbUsers.Users select u).ToList();
            foreach (Users _user in users)
            {
                var basket = (from b in dbBasket.Basket where b.UserID == _user.UserID select b.GoodID).ToList();
                var goods = (from good in dbGoods.Goods
                             where basket.Contains(good.GoodID)
                             select good).ToList();
                UserGoodsModel _uGoods = new UserGoodsModel(_user);
                _uGoods.Goods = GoodsModel.GetGoods(goods, basket);
                userGoods.Add(_uGoods);
            }
            return View(userGoods);
        }

        public ActionResult Edit(UserRuleModel u)
        {             
            // edit mode
            var users = (from usr in dbUsers.Users where usr.UserID == u.Id select usr).ToList();
            Users user = users[0];
            user.IsAdmin = u.IsAdmin != null;
            try
            {
                dbUsers.SaveChanges();
            }
            catch (System.Data.UpdateException e)
            {
                //Can not insert to database
            }
            return this.RedirectToAction("Index");
        }

    }
}
